﻿using UnityEngine;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Collections;
using System;

public class RoomMgr : SingletonMono<RoomMgr>
{
    public bool isMyRoom;
    [SerializeField]
    public RoomData curRoom;

    public List<RoomData> allRoomList = new List<RoomData>();

    public Dictionary<string, float> room_heartBeat = new Dictionary<string, float>(); //房间心跳，用来检测房间是否还存在


    public float room_timeOut = 2f; //超时房间

    public bool isCheckRoom; //是否检查房间

    public float second_check = 2f;//多少秒检测一次 房间列表

    #region 房间操作
    /// <summary>
    /// 创建房间
    /// </summary>
    /// <param name="map"></param>
    /// <param name="roomName"></param>
    public void RequestCreateRoom(MapData map,string roomName = "")
    {
        curRoom = new RoomData();
        curRoom.map = map;
        
        curRoom.GUID = Guid.NewGuid().ToString();
        curRoom.allPlayers.Add(Global.Instantce.Actor);
        curRoom.owner = curRoom.allPlayers[0];
        if (string.IsNullOrEmpty(roomName))
            roomName = curRoom.owner.name + "的房间";
        curRoom.roomName = roomName;
        for (int i = 0; i < curRoom.map.maxPlayer; i++)
            curRoom.readyList.Add(false);
        isMyRoom = true;
        NetHandler.Instantce.CreateRoom();
        UIManager.Instantce.Open(UIConst.UI_Room);
    }

    public void RequestJoinRoom(RoomData room)
    {
        NetHandler.Instantce.JoinRoom(room);
    }

    public void HandlerJoinRoomResp(RoomData room)
    {
        isMyRoom = false;
        curRoom = room;
        UIManager.Instantce.Open(UIConst.UI_Room);
    }
    public void QuitRoom()
    {
        curRoom = null;
        isMyRoom = false;
        NetHandler.Instantce.QuitRoom();
        ClearAllRoom();
        //UIManager.Instantce.Open(UIConst.UI_RoomList, UIOpenType.CloseLast);
    }

    /// <summary>
    /// 是否满人
    /// </summary>
    /// <returns></returns>
    public bool isCanJoin()
    {
        return curRoom.allPlayers.Count < curRoom.map.maxPlayer;
    }
    public bool OtherRequestJointRoom(ActorData actor)
    {
        if (isCanJoin())
        {
            curRoom.allPlayers.Add(actor);
            EventCentre.Instantce.NotifyEvent(EventDefine.OnOtherJoinRoom, new EventObject(actor));
            return true;
        }
        else
            return false;
    }
    public bool OtherLeaveRoom(string guid)
    {
        var player = curRoom.allPlayers.Find(x => x.actorGUID == guid);
        if(player != null)
        {
            curRoom.allPlayers.Remove(player);
            EventCentre.Instantce.NotifyEvent(EventDefine.OnOtherLeaveRoom, new EventObject(player));
            return true;
        }
        return false;
    }


    public void SendStartGame()
    {
        if (!isMyRoom)
            return;
        NetHandler.Instantce.SendStartGame();
        StartGame();
    }
    /// <summary>
    /// 设置开始游戏
    /// </summary>
    public void StartGame()
    {
        if(curRoom != null)
        {
            curRoom.isGameStart = true;
            ClearAllRoom();

            GameManager.Instantce.InitGame(curRoom);
        }
    }
    #endregion
    #region 房间检索
    public void StartCheckRoom()
    {
        if (!isCheckRoom)
        {
            isCheckRoom = true;
            StartCoroutine(CheckRoom_Loop());
        }
    }
    public void EndCheckRoom()
    {
        isCheckRoom = false;
    }
    IEnumerator CheckRoom_Loop()
    {
        while (isCheckRoom)
        {
            yield return new WaitForSeconds(second_check);
            NetHandler.Instantce.CheckRoom();
        }

    }
    #endregion


    public void HandlerDiscoverRoom(RoomData room_data)
    {
        //if (room_data.owner.actorGUID == Global.Instantce.Actor.actorGUID)
        //    return;
        var roomIndex =  allRoomList.FindIndex(x => x.GUID == room_data.GUID);
        if (roomIndex >= 0)
        {
            allRoomList[roomIndex] = room_data;
            room_heartBeat[room_data.GUID] = 0;
        }
        else
        {
            allRoomList.Add(room_data);
            room_heartBeat.Add(room_data.GUID, 0);
        }
            

        
        
        Log.InfoFormat("发现房间 \n {0}", Log.Color_Purple, room_data.ToString());

        EventCentre.Instantce.NotifyEvent(EventDefine.OnRoomListUpdate, new EventObject(allRoomList));
    }

 

    List<string> removeRoomList = new List<string>();
    private void Update()
    {
        if (!isCheckRoom)
            return;

        foreach(var room_heart in allRoomList)
        {
            room_heartBeat[room_heart.GUID] += Time.deltaTime;
            if(room_heartBeat[room_heart.GUID] >= room_timeOut)
            {
                removeRoomList.Add(room_heart.GUID);
            }
        }
        int count = removeRoomList.Count;
        ///移除超时的房间
        foreach (var remove in removeRoomList)
        {
            var roomIndex = allRoomList.FindIndex(x => x.GUID == remove);
            if(roomIndex >= 0)
            {
                allRoomList.RemoveAt(roomIndex);
                room_heartBeat.Remove(remove);
            }
        }
        if(count > 0)
        {
            EventCentre.Instantce.NotifyEvent(EventDefine.OnRoomListUpdate, new EventObject(allRoomList));
        }
        removeRoomList.Clear();
    }


    private void ClearAllRoom()
    {
        allRoomList.Clear();
        room_heartBeat.Clear();
    }
}
